package com.hzhc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.common.Constants;
import com.hzhc.common.UserConstants;
import com.hzhc.dto.LayuiSelectTreeVo;
import com.hzhc.dto.MetaDto;
import com.hzhc.dto.RouterDto;
import com.hzhc.entity.SysMenu;
import com.hzhc.entity.SysRoleMenu;
import com.hzhc.mapper.SysMenuMapper;
import com.hzhc.service.SysMenuService;
import com.hzhc.utils.ResultUtil;
import com.hzhc.utils.SecurityUtils;
import com.hzhc.vo.SysMenuVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author duanhm
 * @since 2019-07-26
 */
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    private final Integer PID = 0;

    private final SysMenuMapper menuMapper;

    @Override
    public List<SysMenu> findMenuListAll(String searchData, Integer sysType) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        if (StrUtil.isNotBlank(searchData)) {
            queryWrapper.like("name", searchData);
        }
        if (sysType != null) {
            queryWrapper.like("sys_type", sysType);
        }
        queryWrapper.orderByAsc("type");
        queryWrapper.orderByAsc("parent_id");
        queryWrapper.orderByAsc("order_num");
        return menuMapper.selectList(queryWrapper);
    }

    @Override
    public List<SysMenuVo> getSecondRouters(String searchData,Long userId) {
        if (SecurityUtils.isAdmin(userId)){
            return menuMapper.getSecondRoutersAll(searchData);
        }else{
            return menuMapper.getSecondRoutersByUserId(searchData,userId);
        }
    }



    @Override
    public ResultUtil<T> saveMenu(SysMenu datas) {
        datas.setCreateTime(LocalDateTime.now());
        boolean b = save(datas);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> updateMenu(SysMenu datas) {
        SysMenu sysMenu = menuMapper.selectById(datas.getId());
        sysMenu.setIcon(datas.getIcon());
        sysMenu.setName(datas.getName());
        sysMenu.setParentId(datas.getParentId());
        sysMenu.setType(datas.getType());
        sysMenu.setUrl(datas.getUrl());
        sysMenu.setOrderNum(datas.getOrderNum());
        sysMenu.setModuleUrl(datas.getModuleUrl());
        sysMenu.setPermission(datas.getPermission());
        sysMenu.setShowStatus(datas.getShowStatus());
        sysMenu.setMenuStatus(datas.getMenuStatus());
        boolean b = updateById(sysMenu);
        return b ? ResultUtil.ok() : ResultUtil.fail();
    }

    @Override
    public ResultUtil<T> delMenu(Long id) {
        int bol = menuMapper.deleteById(id);
        if (bol == 1) {
            return ResultUtil.ok();
        } else {
            return ResultUtil.fail();
        }
    }

    @Override
    public List<SysMenu> getGrantTreeMenu(Long id, Integer sysType, Integer systemId) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        if (sysType != null) {
            queryWrapper.eq("sys_type", sysType);
        }
        List<SysMenu> list = menuMapper.selectList(queryWrapper);
        SysRoleMenu roleMenu = new SysRoleMenu();
        roleMenu.setRoleId(id);
        return list;
    }

    @Override
    public List<LayuiSelectTreeVo> getSelectTreeMenu(SysMenu sysMenu) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        if (sysMenu.getSysType() != null) {
            queryWrapper.eq("sys_type", sysMenu.getSysType());
        }
        List<SysMenu> list = menuMapper.selectList(queryWrapper);
        return getLayuiMenuTree(list, true, null);
    }

    @Override
    public List<LayuiSelectTreeVo> getSelectMlTreeMenu(SysMenu sysMenu) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        if (sysMenu.getSysType() != null) {
            queryWrapper.eq("sys_type", sysMenu.getSysType());
        }
//        queryWrapper.eq("type",0);
        List<SysMenu> list = menuMapper.selectList(queryWrapper);
        return getLayuiMenuMlTree(list, true);
    }

    /**
     * 生成菜单树
     *
     * @param menuList
     * @return
     */
    public static List<LayuiSelectTreeVo> getLayuiMenuTree(List<SysMenu> menuList, Boolean isAll,
                                                           List<SysRoleMenu> rolemenulist) {
        List<LayuiSelectTreeVo> retlist = new ArrayList<LayuiSelectTreeVo>();
        for (SysMenu menu : menuList) {
            if (menu.getType() == 0 && menu.getParentId()==0) {// 目录类型 菜单列表过滤掉 独立的发运和到达业务
                LayuiSelectTreeVo vo = new LayuiSelectTreeVo();
                vo.setId(menu.getId().intValue());
                vo.setName(menu.getName());
                vo.setLabel(menu.getName());
                if (menu.getType() == 1) {
                    vo.setOpen(false);
                }
                if (isCheckMenu(rolemenulist, menu.getId())) {
                    vo.setChecked(true);
                }
                doChildrenList(menuList, vo, isAll, rolemenulist);
                retlist.add(vo);
            }
        }

        return retlist;
    }

    public static List<LayuiSelectTreeVo> getLayuiMenuMlTree(List<SysMenu> menuList, Boolean isAll) {
        List<LayuiSelectTreeVo> retlist = new ArrayList<LayuiSelectTreeVo>();
        for (SysMenu menu : menuList) {
            if (menu.getType() == 0) {// 目录类型
                LayuiSelectTreeVo vo = new LayuiSelectTreeVo();
                vo.setId(menu.getId().intValue());
                vo.setName(menu.getName());
                vo.setLabel(menu.getName());
                doChildrenList1(menuList, vo, isAll);
                if(menu.getParentId()==0){
                    retlist.add(vo);
                }
            }
        }

        return retlist;
    }

    private static Boolean isCheckMenu(List<SysRoleMenu> rolemenulist, Long menuid) {
        if (rolemenulist == null || rolemenulist.size() == 0) {
            return false;
        }
        for (SysRoleMenu rolemenu : rolemenulist) {
            if (rolemenu.getMenuId().equals(menuid)) {
                return true;
            }
        }
        return false;

    }

    private static void doChildrenList(List<SysMenu> childrenList, LayuiSelectTreeVo pvo, Boolean isAll,
                                       List<SysRoleMenu> rolemenulist) {
        if (childrenList != null && childrenList.size() > 0) {
            List<LayuiSelectTreeVo> retlist = new ArrayList<LayuiSelectTreeVo>();
            for (SysMenu menu : childrenList) {
                if (pvo.getId().intValue() == menu.getParentId()) {
                    LayuiSelectTreeVo vo = new LayuiSelectTreeVo();
                    vo.setId(menu.getId().intValue());
                    vo.setName(menu.getName());
                    vo.setLabel(menu.getName());
                    if (menu.getType() == 1) {
                        vo.setOpen(false);
                    }
                    if (isCheckMenu(rolemenulist, menu.getId())) {
                        vo.setChecked(true);
                    }
                    if (menu.getType() != 2) {
                        doChildrenList(childrenList, vo, isAll, rolemenulist);
                    }
                    if (isAll) {
                        retlist.add(vo);
                    } else {
                        if (menu.getType() != 2) {
                            retlist.add(vo);
                        }

                    }

                }
            }
            if (retlist.size() > 0) {
                pvo.setChildren(retlist);
            }

        }

    }
    private static void doChildrenList1(List<SysMenu> childrenList, LayuiSelectTreeVo pvo, Boolean isAll) {
        if (childrenList != null && !childrenList.isEmpty()) {
            List<LayuiSelectTreeVo> retlist = new ArrayList<LayuiSelectTreeVo>();
            for (SysMenu menu : childrenList) {
                if (pvo.getId().equals(menu.getParentId().intValue()) ) {
                    LayuiSelectTreeVo vo = new LayuiSelectTreeVo();
                    vo.setId(menu.getId().intValue());
                    vo.setName(menu.getName());
                    vo.setLabel(menu.getName());
//                    if (menu.getType() == 1) {
//                        vo.setOpen(false);
//                    }
                    if (menu.getType() ==0) {
                        doChildrenList1(childrenList, vo, isAll);
                    }
                    if (isAll) {
                        retlist.add(vo);
                    } else {
                        if (menu.getType() == 0) {
                            retlist.add(vo);
                        }
                    }

                }
            }
            if (!retlist.isEmpty()) {
                pvo.setChildren(retlist);
            }

        }

    }

    @Override
    public List<SysMenuVo> selectMenuTreeByUserId(Long userId) {
        List<SysMenuVo> menus;
        if (SecurityUtils.isAdmin(userId)){
            //如果是管理员则获取所有权限菜单
            menus = menuMapper.selectMenuTreeAll();
        }else{
            //根据用户获取权限菜单
            menus = menuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, PID);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenuVo> getChildPerms(List<SysMenuVo> list, int parentId) {
        List<SysMenuVo> returnList = new ArrayList<SysMenuVo>();
        for (SysMenuVo t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<SysMenuVo> list, SysMenuVo t) {
        // 得到子节点列表
        List<SysMenuVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenuVo tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }


    /**
     * 得到子节点列表
     */
    private List<SysMenuVo> getChildList(List<SysMenuVo> list, SysMenuVo t) {
        List<SysMenuVo> tlist = new ArrayList<>();
        for (SysMenuVo n : list) {
            if (n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }


    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenuVo> list, SysMenuVo t) {
        return !getChildList(list, t).isEmpty();
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterDto> buildMenus(List<SysMenuVo> menus)
    {
        List<RouterDto> routers = new LinkedList<RouterDto>();
        for (SysMenuVo menu : menus)
        {
            RouterDto router = new RouterDto();
            router.setMenuId(menu.getId());
            router.setHidden(menu.getShowStatus()==1);
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
//			router.setQuery(menu.getQuery());
            router.setMeta(new MetaDto(menu.getName(), menu.getIcon(),menu.getShowStatus()==0));
            List<SysMenuVo> cMenus = menu.getChildren();
            if (cMenus != null && !cMenus.isEmpty() && menu.getType() == 0){
                router.setAlwaysShow(true);
                router.setRedirect("");
                router.setChildren(buildMenus(cMenus));
            }else if(menu.getType() == 1){
                //按钮权限
                if (cMenus != null && !cMenus.isEmpty()){
                    List<String> permissionList = cMenus.stream().map(SysMenuVo::getPermission).collect(Collectors.toList());
                    router.setPermissionList(permissionList);
                }
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenuVo menu){
        String routerName = StringUtils.capitalize(menu.getUrl());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuVo menu)
    {
        String routerPath = menu.getUrl();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 1)
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (1 == menu.getParentId().intValue() && menu.getType() == 0)
        {
            routerPath = "/" + menu.getUrl();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }


    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuVo menu){
        return menu.getParentId().intValue() == PID && menu.getType() == 1;
    }


    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path)
    {
        return StringUtils.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS, Constants.WWW, "." },
                new String[] { "", "", "", "/" });
    }


    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuVo menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getModuleUrl()) && !isMenuFrame(menu))
        {
            component = menu.getModuleUrl();
        }
        else if (StringUtils.isEmpty(menu.getModuleUrl()) && menu.getParentId().intValue() != PID)
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getModuleUrl()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenuVo menu)
    {
        return menu.getParentId().intValue() != PID && menu.getType() == 0;
    }



}
